package cc.magicjson.scenario.implement.module.bean;

import java.util.*;

public class Lottery {

    public static void main(String[] args) {
        // 假设有 100 万用户的 ID 为 1 到 1000000
        int totalUsers = 1_000_000;
        int winnersCount = 10;

        // 奖品池
        List<String> prizes = Arrays.asList("奖品A", "奖品B", "奖品C", "奖品D", "奖品E",
                                            "奖品F", "奖品G", "奖品H", "奖品I", "奖品J");
        if (prizes.size() != winnersCount) {
            throw new IllegalArgumentException("奖品数量必须等于中奖人数");
        }

        // 抽取10个中奖者
        List<Integer> winners = drawWinners(totalUsers, winnersCount);

        // 将奖品随机分配给中奖者
        Map<Integer, String> result = assignPrizes(winners, prizes);

        // 打印结果
        System.out.println("中奖名单及奖品分配如下：");
        result.forEach((user, prize) -> System.out.println("用户ID: " + user + " 奖品: " + prize));
    }

    /**
     * 抽取中奖用户
     *
     * @param totalUsers   总用户数
     * @param winnersCount 需要抽取的中奖人数
     * @return 中奖用户列表
     */
    public static List<Integer> drawWinners(int totalUsers, int winnersCount) {
        Random random = new Random();
        List<Integer> users = new ArrayList<>();
        for (int i = 1; i <= totalUsers; i++) {
            users.add(i);
        }

        // 使用 Fisher-Yates 洗牌算法，只洗前 winnersCount 个用户
        for (int i = 0; i < winnersCount; i++) {
            int randomIndex = i + random.nextInt(totalUsers - i);
            Collections.swap(users, i, randomIndex);
        }

        // 返回前 winnersCount 个用户
        return users.subList(0, winnersCount);
    }

    /**
     * 分配奖品
     *
     * @param winners 中奖者列表
     * @param prizes  奖品列表
     * @return 中奖者和奖品的对应关系
     */
    public static Map<Integer, String> assignPrizes(List<Integer> winners, List<String> prizes) {
        Collections.shuffle(prizes); // 随机打乱奖品顺序
        Map<Integer, String> result = new HashMap<>();
        for (int i = 0; i < winners.size(); i++) {
            result.put(winners.get(i), prizes.get(i));
        }
        return result;
    }
}
